const router = require("express").Router();
const mysql = require("./../mysql");
const Review = require("./../mysql/collection/Review");
const Order = require("./../mysql/collection/Order");
const User = require("./../mysql/collection/User");

/**
 * @api {get} /admin/review/list 获取评价列表
 * @apiName getReviewList
 * @apiGroup AdminReview
 * @apiHeader {String} token  管理员token
 * @apiParam {Number} [page=1] 页码
 * @apiParam {Number} [pageSize=10] 每页数量
 * @apiParam {Number} [rating] 评分筛选（1-5）
 * @apiParam {String} [keyword] 关键词搜索（评价内容）
 * @apiSuccessExample {json} Success-Response:
 *  {
 *    code: '200',
 *    message: '获取评价列表成功',
 *    data: {
 *      list: [],
 *      total: 0,
 *      page: 1,
 *      pageSize: 10
 *    }
 *  }
 */
router.get("/list", (req, res, next) => {
  const { page = 1, pageSize = 10, rating, keyword } = req.query;
  
  const pageNum = parseInt(page);
  const pageSizeNum = parseInt(pageSize);
  const skip = (pageNum - 1) * pageSizeNum;
  
  // 构建查询条件
  let query = {};
  if (rating && rating >= 1 && rating <= 5) {
    query.rating = parseInt(rating);
  }
  if (keyword && keyword.trim()) {
    query.content = { $regex: keyword.trim(), $options: 'i' };
  }
  
  // 获取总数
  mysql.find(Review, query)
    .then(allReviews => {
      const total = allReviews.length;
      
      // 获取分页数据，按创建时间倒序
      return mysql.find(
        Review,
        query,
        { _id: 0, __v: 0 },
        { created_at: -1 },
        skip,
        pageSizeNum
      ).then(reviews => {
        // 获取每个评价对应的订单和用户信息
        const promises = reviews.map(async (review) => {
          const [orderInfo, userInfo] = await Promise.all([
            mysql.find(Order, { orderid: review.orderid }, {
              orderid: 1,
              proname: 1,
              img1: 1,
              discount: 1,
              num: 1,
              _id: 0
            }),
            mysql.find(User, { userid: review.userid }, {
              userid: 1,
              username: 1,
              phone: 1,
              _id: 0
            })
          ]);
          
          return {
            ...review,
            orderInfo: orderInfo[0] || {},
            userInfo: userInfo[0] || {}
          };
        });
        
        return Promise.all(promises).then(reviewsWithInfo => {
          res.send({
            code: "200",
            message: "获取评价列表成功",
            data: {
              list: reviewsWithInfo,
              total,
              page: pageNum,
              pageSize: pageSizeNum
            }
          });
        });
      });
    })
    .catch(err => {
      console.error('获取评价列表失败:', err);
      res.send({
        code: "500",
        message: "获取评价列表失败"
      });
    });
});

/**
 * @api {delete} /admin/review/delete 删除评价
 * @apiName deleteReview
 * @apiGroup AdminReview
 * @apiHeader {String} token  管理员token
 * @apiParam {String} reviewid 评价ID
 * @apiSuccessExample {json} Success-Response:
 *  {
 *    code: '200',
 *    message: '删除评价成功'
 *  }
 */
router.delete("/delete", (req, res, next) => {
  const { reviewid } = req.body;
  
  if (!reviewid) {
    return res.send({
      code: "400",
      message: "评价ID不能为空"
    });
  }
  
  // 检查评价是否存在
  mysql.find(Review, { reviewid })
    .then(reviews => {
      if (reviews.length === 0) {
        return res.send({
          code: "404",
          message: "评价不存在"
        });
      }
      
      // 删除评价
      return mysql.delete(Review, { reviewid }).then(() => {
        res.send({
          code: "200",
          message: "删除评价成功"
        });
      });
    })
    .catch(err => {
      console.error('删除评价失败:', err);
      res.send({
        code: "500",
        message: "删除评价失败"
      });
    });
});

/**
 * @api {get} /admin/review/statistics 评价统计
 * @apiName getReviewStatistics
 * @apiGroup AdminReview
 * @apiHeader {String} token  管理员token
 * @apiSuccessExample {json} Success-Response:
 *  {
 *    code: '200',
 *    message: '获取评价统计成功',
 *    data: {
 *      total: 100,
 *      ratingDistribution: {
 *        1: 5,
 *        2: 10,
 *        3: 20,
 *        4: 30,
 *        5: 35
 *      },
 *      averageRating: 4.2,
 *      recentReviews: []
 *    }
 *  }
 */
router.get("/statistics", (req, res, next) => {
  mysql.find(Review, {}, { _id: 0, __v: 0 })
    .then(reviews => {
      const total = reviews.length;
      
      if (total === 0) {
        return res.send({
          code: "200",
          message: "获取评价统计成功",
          data: {
            total: 0,
            ratingDistribution: { 1: 0, 2: 0, 3: 0, 4: 0, 5: 0 },
            averageRating: 0,
            recentReviews: []
          }
        });
      }
      
      // 计算评分分布
      const ratingDistribution = { 1: 0, 2: 0, 3: 0, 4: 0, 5: 0 };
      let totalRating = 0;
      
      reviews.forEach(review => {
        ratingDistribution[review.rating]++;
        totalRating += review.rating;
      });
      
      // 计算平均评分
      const averageRating = Math.round((totalRating / total) * 10) / 10;
      
      // 获取最近的评价（最多10条）
      const recentReviews = reviews
        .sort((a, b) => new Date(b.created_at) - new Date(a.created_at))
        .slice(0, 10);
      
      // 获取最近评价的订单和用户信息
      const promises = recentReviews.map(async (review) => {
        const [orderInfo, userInfo] = await Promise.all([
          mysql.find(Order, { orderid: review.orderid }, {
            proname: 1,
            img1: 1,
            _id: 0
          }),
          mysql.find(User, { userid: review.userid }, {
            username: 1,
            _id: 0
          })
        ]);
        
        return {
          reviewid: review.reviewid,
          rating: review.rating,
          content: review.content,
          created_at: review.created_at,
          proname: orderInfo[0]?.proname || '',
          username: userInfo[0]?.username || ''
        };
      });
      
      return Promise.all(promises).then(recentReviewsWithInfo => {
        res.send({
          code: "200",
          message: "获取评价统计成功",
          data: {
            total,
            ratingDistribution,
            averageRating,
            recentReviews: recentReviewsWithInfo
          }
        });
      });
    })
    .catch(err => {
      console.error('获取评价统计失败:', err);
      res.send({
        code: "500",
        message: "获取评价统计失败"
      });
    });
});

/**
 * @api {get} /admin/review/detail/:reviewid 获取评价详情
 * @apiName getReviewDetail
 * @apiGroup AdminReview
 * @apiHeader {String} token  管理员token
 * @apiParam {String} reviewid 评价ID
 * @apiSuccessExample {json} Success-Response:
 *  {
 *    code: '200',
 *    message: '获取评价详情成功',
 *    data: {
 *      reviewid: 'review_xxx',
 *      orderid: 'order_xxx',
 *      userid: 'user_xxx',
 *      rating: 5,
 *      content: '商品质量很好',
 *      created_at: '2024-01-01T00:00:00.000Z',
 *      orderInfo: {},
 *      userInfo: {}
 *    }
 *  }
 */
router.get("/detail/:reviewid", (req, res, next) => {
  const { reviewid } = req.params;
  
  if (!reviewid) {
    return res.send({
      code: "400",
      message: "评价ID不能为空"
    });
  }
  
  mysql.find(Review, { reviewid }, { _id: 0, __v: 0 })
    .then(reviews => {
      if (reviews.length === 0) {
        return res.send({
          code: "404",
          message: "评价不存在"
        });
      }
      
      const review = reviews[0];
      
      // 获取订单和用户信息
      return Promise.all([
        mysql.find(Order, { orderid: review.orderid }, { _id: 0, __v: 0 }),
        mysql.find(User, { userid: review.userid }, { 
          userid: 1,
          username: 1,
          phone: 1,
          email: 1,
          _id: 0
        })
      ]).then(([orderInfo, userInfo]) => {
        res.send({
          code: "200",
          message: "获取评价详情成功",
          data: {
            ...review,
            orderInfo: orderInfo[0] || {},
            userInfo: userInfo[0] || {}
          }
        });
      });
    })
    .catch(err => {
      console.error('获取评价详情失败:', err);
      res.send({
        code: "500",
        message: "获取评价详情失败"
      });
    });
});

module.exports = router;